package com.codeoss.framework.webide.app.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.impexp.ExportManager;
import com.codeoss.framework.impexp.ImportManager;
import com.codeoss.framework.webide.app.service.CommonAppDataHandler;
import com.codeoss.module.ir.model.IrApplication;
import com.codeoss.module.ir.model.IrPage;
import com.codeoss.module.ir.service.IIrPageService;

@Service("ir_pageAppDataHandler")
public class IrPageAppDataHandler extends CommonAppDataHandler {
	@Autowired
	private IIrPageService irPageService;
	@Autowired
	private ExportManager exportManager;
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private ImportManager importManager;
	@Override
	public void dataExport(YunContext yunContext, IrApplication irApplication, String tableName) throws IOException {
		// TODO Auto-generated method stub
		QueryWrapper<IrPage> queryWrapper = new QueryWrapper<IrPage>();
		queryWrapper.in("module_type", getModuleTypeList(yunContext, irApplication));
		queryWrapper.orderByAsc("id");
		List<IrPage> irPageList = irPageService.list(queryWrapper);
		for (int i = 0; i < irPageList.size(); i++) {
			IrPage irPage = irPageList.get(i);
			Table table = tableStore.get("ir_page");
			Query query = new Query();
			query.add(Restrictions.eq("page_code", irPage.getPageCode()));
			String filename = "ir_page" + i;
			writeConfigKeyValue(yunContext, "ir_page", filename);
			FileOutputStream os = createFileOutputStream(yunContext, filename);
			exportManager.exportProperties(yunContext, table, query, os);
			os.close();
		}
	}

	@Override
	@Transactional
	public void dataImport(YunContext yunContext, IrApplication irApplication, String tableName,
			List<String> filenameList) throws IOException {
		// TODO Auto-generated method stub
		if (filenameList == null) {
			return;
		}
		for(int i=0;i<filenameList.size();i++) {
			String filename=filenameList.get(i);
			InputStream is=createFileInputStream(yunContext, filename);
			Table table = tableStore.get("ir_page");
			importManager.importProperties(yunContext, table, is);
			is.close();
		}
	}

}
